package array;

import java.util.Arrays;

//缺失的第一个正数
public class leetcode41 {
    public static void main(String[] args) {
        int[] nums = {3,4,-1,1};
        int min = firstMissingPositive3(nums);
        System.out.println(min);
    }

    public static int firstMissingPositive(int[] nums) {
        int min = 1;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == min){
                min++;
            }
        }

        return min;
    }

    public static int firstMissingPositive2(int[] nums) {
        int n = nums.length;
        // 1. 将非正数替换为 n+1
        for (int i = 0; i < n; i++) {
            if (nums[i] <= 0) nums[i] = n + 1;
        }
        // 2. 标记出现过的数
        for (int i = 0; i < n; i++) {
            int num = Math.abs(nums[i]);
            if (num <= n) {
                nums[num - 1] = -Math.abs(nums[num - 1]);
            }
        }
        // 3. 查找第一个正数
        for (int i = 0; i < n; i++) {
            if (nums[i] > 0) return i + 1;
        }
        return n + 1;
    }

    public static int firstMissingPositive3(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
                swap(nums, i, nums[i] - 1);
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] != i + 1) return i + 1;
        }
        return n + 1;
    }

    private static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

}
